<?php
require_once dirname(__FILE__) . '/common/common.inc.php';
require_once dirname(__FILE__) . "/database/$database/database.inc.php";

$renamed = true;
$overwrite = true; 
$max = 1000000; 

if (isset($_FILES['Filedata']) && is_uploaded_file($_FILES['Filedata']['tmp_name']) && $_FILES['Filedata']['error'] == 0) {
  //获得上传文件信息
  $upload_file = $_FILES['Filedata'];
  //获取文件扩展名
  $file_info = pathinfo($upload_file['name']);
  $file_ext = (isset($file_info['extension'])) ? $file_info['extension'] : '';
  
  //获取客户端参数
  $directory = $_POST['directory'];
  $query = json_decode($_POST['query']);
  $hasThumb = ($query && isset($query->t)) ? $query->t : false;
  
  //设置上传的路径
  //建立文件夹
  $updir = UPDIR;
  $upload_path = $updir . $directory;
  create($upload_path);
  
  $unique_id = $upload_file['name'];
  $path = $upload_path . $upload_file['name'];
  //需要重命名否?
  if($renamed){
    $unique_id = 'f' . (time() * rand()) . '.' . $file_ext;
    $path = $upload_path . $unique_id;
  }
  
  //检查文件是否存在
  if (file_exists($path)) {
    if($overwrite) {
      @unlink($path);
    } else {
      $j = 0;
      do {
        $j++;
        $tmp = str_replace('.' . $file_ext, '(' . $j . ').' . $file_ext, $path);
      }
      while (file_exists($temp_file));
      $path = $tmp;
      unset($tmp);
      unset($j);
    }
  }

  if ($upload_file['size'] && $upload_file['size'] < $max && $hasThumb) {
    if (strtolower($file_ext) == 'jpg' || strtolower($file_ext) == 'jpeg') {
      $im = imagecreatefromjpeg($upload_file["tmp_name"]);
    } else if (strtolower($file_ext) == 'png') {
      $im = imagecreatefrompng($upload_file["tmp_name"]);
    } else if (strtolower($file_ext) == 'gif') {
      $im = imagecreatefromgif($upload_file["tmp_name"]);
    }
    if ($im) {
      $width = imagesx($im);
      $height = imagesy($im);
      
      if (file_exists($upload_file['smallname'])) {
        unlink($upload_file['smallname']);
      }
      ResizeImage($im, 50, 50, $upload_file['smallname']);
      ImageDestroy($im);
    } else {
      exit(0);
    }
  }
  
  if (move_uploaded_file($upload_file['tmp_name'], $path)) {
    //Add custom code here...
    try {
      $hostname = DB_HOST;
      $username = DB_LOGIN;
      $password = DB_PASS;
      $dbname = DB_NAME;
      $myPdo = new PDO ('mysql:host=' . $hostname, $username, $password);
      $myPdo->exec('USE ' . $dbname);
      $myPdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
      echo ERROR_SIGN . $e->getMessage();
    }
    
    try {
      $myPdo->beginTransaction();
      $file = new stdClass();
      $file->track_id = 'u' . (time() * rand());
      $file->client_id = ($query && isset($query->c)) ? $query->c : 0;
      $file->visa_track_id = ($query && isset($query->v)) ? $query->v : 0;
      $file->name = $upload_file['name'];
      $file->unique_id = $unique_id;
      $file->type = ($query && isset($query->f)) ? $query->f : '';
      $file->size = ($upload_file['size']) ? $upload_file['size'] : 0;
      $file->link = $path;
      $myPdo->exec(MiscUtils::obj2Ins('pz_file', $file ));
      $file->id = $myPdo->lastInsertId();
      echo json_encode($file);
      $myPdo->commit();
    } catch (PDOException $e) {
      echo ERROR_SIGN . $e->getMessage();
    }
  }
} 
  
//若没有这个文件夹，则需要创建文件夹
function create($dir) {
  if (!is_dir($dir)) {
    $temp = explode('/',$dir);
    $cur_dir = '';
    for($i = 0; $i < count($temp); $i++) {
      $cur_dir .= $temp[$i].'/';
      if (!is_dir($cur_dir)) {
        @mkdir($cur_dir, 0777);
      }
    }
  }
}

function ResizeImage($im, $maxwidth, $maxheight, $name){
  $width = imagesx($im);
  $height = imagesy($im);
  if (($maxwidth && $width > $maxwidth) || ($maxheight && $height > $maxheight)) {
    $RESIZEWIDTH = false;
    $RESIZEHEIGHT = false;
    if ($maxwidth && $width > $maxwidth) {
      $widthratio = $maxwidth/$width;
      $RESIZEWIDTH = true;
    }
    if ($maxheight && $height > $maxheight) {
      $heightratio = $maxheight/$height;
      $RESIZEHEIGHT = true;
    }
    if ($RESIZEWIDTH && $RESIZEHEIGHT) {
      if ($widthratio < $heightratio) {
        $ratio = $widthratio;
      } else {
        $ratio = $heightratio;
      }
    } else if ($RESIZEWIDTH) {
      $ratio = $widthratio;
    } else if ($RESIZEHEIGHT) {
      $ratio = $heightratio;
    }
    $newwidth = $width * $ratio;
    $newheight = $height * $ratio;
    if (function_exists("imagecopyresampled")) {
      $newim = imagecreatetruecolor($newwidth, $newheight);
      imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    } else {
      $newim = imagecreate($newwidth, $newheight);
      imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    }
    imagejpeg($newim, $name . ".jpg");
    imagedestroy($newim);
  } else {
    imagejpeg($im, $name . ".jpg");
  }
}
?>